import React, {useEffect, useState} from 'react';
import './index.css'
import {useLocation} from "react-router-dom";
import {Image, Spin} from 'antd';
import http from "../../../util/http";
import {message} from "antd";
import orgImg from './org_ins.png'

function ShowImg(props) {
    const location = useLocation();
    const state = location.state || {}
    const params = state.params || {}
    const docId = params.docId || -1
    //文章数据
    const [img, setImg] = useState("");
    //加载状态
    const [loading, setLoading] = useState(false);
    //附件列表
    useEffect(() => {
        setLoading(true)
        http.doGet('/doc/gethtml', {id: docId}).then(res => {
            if (res.status === 200) {

                const imgSrc = getImgSrc(res.content);

                imgSrc.length > 0 && setImg(imgSrc[0])

            } else {
                setImg("")
            }
            setLoading(false)
        }).catch(reason => {
            message.error(reason.message)
            setImg("")
            setLoading(false)
        })
    }, [docId])

    function getImgSrc(htmlStr) {
        let imgSrcArr = [];
        if (htmlStr != null){
            let reg = /<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim;

            let tem;
            while (tem = reg.exec(htmlStr)) {
                imgSrcArr.push(tem[2]);
            }
        }

        return imgSrcArr;
    }

    return (
        <div className="portal-show-img-main">
            <Spin spinning={loading}>
                <div className="portal-show-img-content">
                    <Image
                        src={img === '' ? orgImg : img}
                        width="100%"
                        fallback={orgImg}
                    />
                </div>
            </Spin>
        </div>
    );
}

export default ShowImg;
